<?php

/**
 * @name MvcView
 * @author Roman Metlinskyi
 */

class MvcView extends Object
{

  private static $config;

  private $masterPage;
  private $filename;

  private $model;
  private $controller;

  public static function Init($config)
  {
    self::$config = $config;
  }

  public function __construct($name, $controller)
  {

    $this->controller = $controller;

    // Vierw path
    $this->filename = new String($name);
    if ($this->filename->StartWith('~')) {

    } else {
      $this->filename->Prepend(DIRECTORY_SEPARATOR);
      $this->filename->Prepend($this->controller->Name);
      $this->filename->Prepend(self::$config->directory);
    }
    $this->filename->Append('.php');

    // Master page path
    if($this->controller->masterPage){
      $this->masterPage = new String($this->controller->masterPage);
      $this->masterPage->Prepend(self::$config->directory);
      $this->masterPage->Append('.master.php');
    }
  }

  public function Model($model)
  {
    $this->model = $model;
    return $this;
  }

  public function Render()
  {
    $model = $this->model;

    // Render view
    ob_start();

    require $this->filename->ToLower();

    $content = ob_get_contents();
    ob_end_clean();

    $this->renderMasterPage($content);

  }

  private function renderMasterPage($output = null)
  {
    if ($this->masterPage != null) {
      return require_once $this->masterPage;
    }

    echo $output;
  }


  public function ToJson()
  {
    My::System()->HttpResponse->MimeType = 'application/json';
    echo json_encode($this->model);
  }

  public function ToXml()
  {
    My::System()->HttpResponse->MimeType = 'text/xml';
    $document = new DOMDocument( );
    foreach ($this->model as $name=>$value){
      $document->createElement( $name , $value);
    }
    echo $document->saveXML( );
  }
}
